<template>
	<view class="wrap">
        <u-navbar
            title-color="#303133"
            :is-fixed="true"
            :is-back="true"
            :background="background"
            :back-text-style="{color: '#303133'}"
            :back-icon-name="backIconName"
            :back-text="backText"
            :back-icon-size="40"
            :border-bottom="false"
            :custom-back="handleClose"
            >
            <view class="slot-wrap" >
                <view @click="backSearch" class="input" >
                    <image class="icon"></image>
                    <text>{{keyword || '请输入关键字'}}</text>
                </view>
            </view>
            <view class="navbar-right" slot="right" v-if="slotRight" @click="slotRightShow = true">
                <view class="message-box right-item">
                    <u-icon name="more-dot-fill" size="38"></u-icon>
                    <!-- <u-badge count="18" size="mini" :offset="[-15, -15]"></u-badge> -->
                </view>
            </view>
        </u-navbar>
        <view class="sort-box">
            <view class="u-flex inner-sort">
                <view class="u-flex-1 u-text-center" :class="tabIndex === 1 ? 'active' : ''" @click="sortsShow = !sortsShow">
                   {{ defSort }}
                   <u-icon class="u-m-l-10" :name="sortsShow ? 'arrow-up-fill' : 'arrow-down-fill'" :color="tabIndex == 1 ? '#ff5000' : '#CACACA'" size="16"></u-icon>
                </view>
                <view class="u-flex-1 u-text-center" :class="tabIndex === 2 ? 'active' : ''" @click="handleClickSort(2, sortsBuynum)">
                    {{ sortsBuynum.title }}
                </view>
                <view class="u-flex-1 u-text-center" :class="tabIndex === 3 ? 'active' : ''" @click="handleClickSort(3, sortsShop)" >
                    店铺
                </view>
                <view class="u-flex-1 u-text-center" @click="doublerowShow = !doublerowShow">
                    <u-icon class="u-m-l-10" :name="doublerowShow ? 'fenlei_liebiao' : 'fenlein'" custom-prefix="custom-icon" size="36"></u-icon>
                </view>
            </view>
            <view v-if="sortsShow">
                <view class="mask-box" @click="sortsShow = false"></view>
                <view class="sort-list">
                    <view class="sort-item u-flex u-row-between" :class="sort.active ? 'active' : ''" v-for="(sort, index) in sorts" :key="index" @click="handleClickSort(1, sort)">
                        <text>{{ sort.title }}</text>
                        <u-icon v-if="sort.active" class="u-m-l-10" name="checkmark"></u-icon>
                    </view>
                </view>
            </view>
        </view>
        <!-- #ifdef H5 -->
        <u-gap height="76" bg-color="#FFFFF"></u-gap>
        <!-- #endif -->
        <!-- #ifdef MP-WEIXIN || APP-PLUS -->
        <u-gap :height="statusBar || customBar" bg-color="#FFFFF"></u-gap>
        <!-- #endif -->
        <view class="swiper-box" v-show="!showSearch">
            <mescroll-body ref="mescrollRef" :top="barHeight + 'rpx'" auto="false" :down="down"  @init="mescrollInit" @up="upCallback">
                <view class="goods-list-view" :class="doublerowShow ? 'u-m-l-20 u-m-t-10 u-m-r-20' : ''" v-if="tabIndex != 3">
                    <view v-for="(item,index) in goodsList" :key="index" :class="[(index + 1) % 2 == 0 ? 'list-b' : '', doublerowShow ? 'goods-list' : '' ]">
                        <view @click="onGoodsDetail(item.goods_id)">
                            <goods-cell-search
                                :doublerowShow="doublerowShow"
                                :goodsName="item.name"
                                :goodsImg="item.small"
                                :goodsPrice="item.price"
                                :goodsBuyCount="item.buy_count"
                                :goodsCommentNum="item.comment_num"
                                :goodsSellerName="item.seller_name"
                                :selfOperated="item.self_operated"
                            ></goods-cell-search>
                        </view>
                    </view>
                </view>

                <view class="shop-list-view" v-if="tabIndex === 3" >
                    <view v-for="(item,index) in shopList" :key="index">
                        <view class="shop-view">
                            <view class="u-flex u-row-between">
                                <view class="u-flex">
                                    <view style="width:230rpx;">
                                        <u-image mode="widthFix" width="100rpx" :src="item.shop_logo" v-if="item.shop_logo"></u-image>
                                        <u-image mode="widthFix" width="100rpx" src="/static/images/icon-no-shop-logo.png" v-else></u-image>
                                    </view>
                                    <view class="u-margin-left-5 u-flex">
                                        <view class="u-flex-1">{{item.shop_name}}</view>
                                        <view class="self u-m-l-10 u-m-r-10" v-if="item.self_operated">自营</view>
                                    </view>
                                </view>
                                <view>
                                    <u-button type="warning" shape="circle" size="mini" @click="goSeller(item)">进店逛逛</u-button>
                                </view>
                            </view>
                            <view class="u-flex u-row-between u-margin-top-16">
                                <view v-for="(goodsItem,goodsIndex) in item.goods_list.slice(0,3)" :key="goodsIndex">
                                    <navigator :url="'/goods-module/goods?goods_id='+goodsItem.goods_id">
                                        <u-image
                                            border-radius="8"
                                            width="200rpx"
                                            height="200rpx"
                                            :src="goodsItem.thumbnail"
                                            >
                                        </u-image>
                                    </navigator>
                                </view>
                            </view>
                        </view>
                    </view>
                </view>
            </mescroll-body>
        </view>

        <!-- 弹出层 -->
        <u-popup v-model="slotRightShow" mode="top" length="22%"  border-radius="20" :mask="false">
            <view class="slot-right-box u-p-l-30 u-p-r-30" :style="{paddingTop: barHeight + 'px'}">
                <view class="u-flex u-row-between u-p-t-20 u-p-b-40 u-font-30">
                    <view class="">
                        功能直达
                    </view>
                    <view class="" @click="slotRightShow = false">
                        <u-icon name="close"></u-icon>
                    </view>
                </view>
                <view class="u-flex slot-right-list u-m-b-20">
                    <view class="slot-right-item" @click="handleMessage">
                        <u-icon label="消息" label-color="#FFFFFF" label-size="24" margin-top="20" label-pos="bottom" size="40" name="xiaoxi" custom-prefix="custom-icon"></u-icon>
                    </view>
                    <view class="slot-right-item" @click="handleHome">
                        <u-icon label="首页" label-color="#FFFFFF" label-size="24" margin-top="20" label-pos="bottom" size="40" name="shouye" custom-prefix="custom-icon"></u-icon>
                    </view>
                    <view class="slot-right-item" @click="handleCart">
                        <u-icon label="购物车" label-color="#FFFFFF" label-size="24" margin-top="20" label-pos="bottom" size="40" name="gouwuche4" custom-prefix="custom-icon"></u-icon>
                    </view>
                    <view class="slot-right-item" @click="handleMine">
                        <u-icon label="我的" label-color="#FFFFFF" label-size="24" margin-top="20" label-pos="bottom" size="40" name="wode4" custom-prefix="custom-icon"></u-icon>
                    </view>
                </view>
            </view>
        </u-popup>
        <view v-if="showSearch" class="searchShow">
            <u-navbar
                title-color="#303133"
                :is-fixed="true"
                :is-back="!isMP"
                :background="background"
                :back-text-style="{color: '#303133'}"
                :back-icon-name="backIconName"
                :back-text="backText"
                :back-icon-size="40"
                :border-bottom="false"
                :custom-back="goBack"
                >
                <view class="slot-wrap" >
                    <view class="search-wrap" v-if="true">
                        <u-search
                            v-model="keyword"
                            :show-action="false"
                            height="70"
                            :action-style="{color: '#fff'}"
                            :border-color="'#fff'"
                            :focus="true"
                            @search="onSearch"
                        ></u-search>
                    </view>
                </view>
                <view class="navbar-right" slot="right" v-if="isMP">
                    <view class="message-box right-item" @click="onClose">
                        取消
                    </view>
                </view>
            </u-navbar>
            <view class="auto-complete" v-if="autoCompleteData">
                <view v-for="(word, index) in autoCompleteData" :key="index" @click="onSearch(word.words)" class="auto-complete-item">
                    <view>{{ word.words }}</view>
                    <view>约{{ word.goods_num }}个商品</view>
                </view>
            </view>
            <view class="history-view" v-if="autoCompleteData.length==0">
                <view class="history-text u-flex u-row-between" v-if="historyList.length != 0">
                    <text>搜索历史</text>
                    <u-icon name="trash" size="40" @click="handleClearHistory"></u-icon>
                </view>
                <view>
                    <u-tag
                        v-for="(keyword,index) in historyList"
                        class="u-margin-right-6 u-margin-top-10"
                        :text="keyword"
                        :mode="'plain'"
                        :shape="'circle'"
                        :type="'info'"
                        :color="'#303133'"
                        :bg-color="'#f3f4f6'"
                        :border-color="'#FFF'"
                        @click="onSearch(keyword)"
                     />
                </view>
                <view class="history-text">
                    搜索发现
                </view>
                <view>
                    <u-tag
                        v-for="(item,index) in hotKeywords"
                        class="u-margin-right-6 u-margin-top-10"
                        :text="item.hot_name"
                        :mode="'plain'"
                        :shape="'circle'"
                        :type="'info'"
                        :color="'#303133'"
                        :bg-color="'#f3f4f6'"
                        :border-color="'#FFF'"
                        @click="hotSearch(item.hot_name)"
                    />
                </view>
            </view>
        </view>
        <loading-view v-if="loading"></loading-view>
	</view>
</template>

<script>
    import * as API_Goods from '@/api/goods.js';
    import * as API_Shop from '@/api/shop.js';
    import * as API_Home from '@/api/home.js';
    import Cache,{Keys} from '@/utils/cache.js';
    // 引入mescroll-mixins.js
    import MescrollMixin from "@/components/mescroll-uni/mescroll-mixins.js";

	export default {
        mixins: [MescrollMixin], // 使用mixin
		data() {
			return {
                //如果是小程序则隐藏
                // #ifdef MP
                isMP: false,
                // #endif
                //如果是不是小程序则展示
                // #ifndef MP
                isMP: true,
                // #endif
                historyList:[],
                hotKeywords:[],
                seller_id: null,
                // 自动补全数据
                autoCompleteData: '',
                // 是否显示搜索层
                showSearch: false,
                //导航栏自定义配置
				backText: '',
				backIconName: 'arrow-left',
				// background: {
				// 	'background-image': 'linear-gradient(45deg, rgb(28, 187, 180), rgb(141, 198, 63))'
				// },
                background: {
                	'background-color': 'white'
                },
                barHeight: this.customBar || this.statusBar, //状态栏高度
                barHeightPx: '',
				keyword: '',
                //如果是小程序则隐藏
				// #ifdef MP
				slotRight: false,
				// #endif
                //如果是不是小程序则展示
				// #ifndef MP
				slotRight: true,
				// #endif
                slotRightShow: false,
                // 排序
                sorts: [
                  { title: '综合', active: true },
                  { title: '价格最低', type: 'price_asc' },
                  { title: '价格最高', type: 'price_desc' },
                  { title: '评论最少', type: 'grade_asc' },
                  { title: '评论最多', type: 'grade_desc' },
                ],
                sortsBuynum: { title: '销量', type: 'buynum_desc' },
                sortsShop: { title: '店铺', type: 'shop_desc' },
                sortsShow: false,
                defSort: '综合',
                doublerowShow: false, //双排显示
                params: {
                  page_no: 1,
                  page_size: 10
                },
                goodsList: [],
                down: {
                    auto: false,
                    use: false,
                },
                shopList: [],
                tabIndex: 1,
                loading: true
			}
		},
        onShow() {
            const _historyList = Cache.getItem(Keys.searchHistory);
            if(!this.$u.test.isEmpty(_historyList)){
                this.historyList = _historyList
            }
        },
        onLoad(options) {
            let that = this
            if(options.seller_id){
                this.seller_id = options.seller_id;
            }
            this.getHotKeywords();
            switch(uni.getSystemInfoSync().platform){
                case 'ios':
                   uni.getSystemInfo({
                   	    success: function (res) {
                   	        if (res.screenWidth === 414 && res.screenHeight === 736) { // 6p 7p 8p
                                that.barHeight = that.barHeight + 25
                            } else if (res.screenWidth === 375 && res.screenHeight === 667) { // 6 7 8
                                that.barHeight = that.barHeight + 35
                            } else if (res.screenWidth === 320 && res.screenHeight === 568) { //5
                                that.barHeight = that.barHeight + 25
                            }
                   	    }
                   	});
                   break;
                default:
                   uni.getSystemInfo({
                   	    success: function (res) {
                   	        if (res.screenWidth === 414 && res.screenHeight === 736) { // 6p 7p 8p
                                that.barHeight = that.barHeight + 25
                            } else if (res.screenWidth === 375 && res.screenHeight === 667) { // 6 7 8
                                that.barHeight = that.barHeight + 35
                            } else if (res.screenWidth === 320 && res.screenHeight === 568) { //5
                                that.barHeight = that.barHeight + 25
                            }
                   	    }
                   	});
                   break;
            }
            this.barHeightPx = 168 + (this.slotRight ? this.statusBar * 2 : this.customBar) + 'rpx'
            this.params = {
                page_no: 1,
                page_size: 10,
                ...options
            }
            if (options.keyword) {
                this.keyword = decodeURIComponent(options.keyword)
                this.params.keyword = this.keyword
            }
        },
        watch: {
            keyword: 'handleSearchChange',
            show(newVal){
                if(!newVal){this.keyword = ''}
            }
        },
		methods: {
            // 跳转
            goSearch(){
                uni.redirectTo({
                    url: '/pages/search/search'
                })
            },
            // 隐藏搜索框页面
            goBack(){
                this.showSearch = false
            },
            //  弹出搜索框页面
            backSearch() {
                this.showSearch = true
                this.keyword = ''
            },
            handleClickSort(index, sort) {
                this.tabIndex = index
                this.$set(this, 'sorts', this.sorts.map(item => {
                  item.active = item.title === sort.title
                  return item
                }))
                if(index != 3){
                    this.defSort = index == 2 ? '综合' : sort.title
                }
                if (sort.type === this.params.sort) return
                this.params.sort = sort.type
                this.params.page_no = 1
                this.goodsList = []
                this.shopList = []
                this.sortsShow = false
                this.mescroll.resetUpScroll(true)
            },
            //搜索店铺
            getShopList(){
                this.params.name = this.params.keyword;
                API_Shop.getShopList(this.params).then(res => {
                    const { data } = res
                    if (data && data.length) {
                        this.shopList.push(...data)
                    }
                    this.loading = false
                    this.mescroll.endBySize(data.length, res.data_total);
                })
            },
            getGoodsList(){
                API_Goods.getGoodsList(this.params).then(res => {
                    const { data } = res.goods_data
                    if (data && data.length) {
                        this.goodsList.push(...data)
                    }
                    this.loading = false
                    this.mescroll.endBySize(data.length, res.goods_data.data_total);
                });
            },
            onGoodsDetail(goodsId){
                uni.navigateTo({
                    url: '/goods-module/goods?goods_id='+goodsId
                })
            },
            //消息
            handleMessage() {
                this.judgeLogin(() => {
                    uni.navigateTo({
                        url:'/mine-module/website-message'
                    });
                })
            },
            //首页
            handleHome() {
                uni.switchTab({
                    url:'/pages/tabs/home/home'
                })
            },
            //购物车
            handleCart() {
                uni.switchTab({
                    url: '/pages/tabs/cart/cart'
                })
            },
            //我的
            handleMine() {
                uni.switchTab({
                    url:'/pages/tabs/mine/mine'
                })
            },
            //上拉加载数据
            upCallback (page){
               this.params.page_no = page.num;
                if (this.tabIndex === 3) {
                    this.getShopList()
                } else {
                    this.getGoodsList()
                }
            },
            //去店铺页
            goSeller(item){
                const _shopInfo = {
                    shop_id: item.shop_id,
                    shop_name: item.shop_name,
                    shop_logo: item.shop_logo,
                    tabNum: 0,
                };
                uni.navigateTo({
                    url: '/pages/shop/shop'+this.$u.queryParams(_shopInfo, true, 'indices'),
                })
            },
            onSearch(e){
                if(this.seller_id == null){
                    //去重，将搜索内容保存到缓存中
                    e && this.historyList.push(e);
                    const newHistoryList = [...new Set(this.historyList)]
                    Cache.setItem(Keys.searchHistory, newHistoryList);
                }

               this.historyList = this.historyList.filter(function(value,index,self){
                   return self.indexOf(value) ===index;
               });
                let _url = `/goods-module/goods-list?keyword=${e}`;
                if(this.seller_id != null){
                    _url += '&seller_id='+this.seller_id;
                }
                uni.redirectTo({
                    url: _url,
                });
            },
            getHotKeywords(){
                API_Home.getHotKeywords().then(res => {
                    this.hotKeywords = res;
                })
            },
            onClose(){
                uni.navigateBack();
            },
            hotSearch(e){
                uni.navigateTo({
                    url: `/goods-module/goods-list?keyword=${e}`
                });
            },
            /** 清空搜索历史 */
            handleClearHistory() {
                uni.showModal({
                    title: '提示',
                    content: '确定要清空搜索历史吗？',
                    confirmColor: '#ff5000',
                    success: (res) => {
                        if(res.confirm) {
                            this.historyList = []
                            Cache.removeItem(Keys.searchHistory)
                        }
                    }
                })
            },
            /** 搜索关键字发生改变 */
            handleSearchChange() {
                let _str = this.keyword
                if (!_str) {
                    this.autoCompleteData = []
                    return
                }
                _str = _str.trim()
                API_Goods.getKeywordNum(_str).then(response => {
                this.autoCompleteData = response
                })
            },
            //自定义返回按钮
            handleClose(){
                console.log('自定义返回')
                const pages = getCurrentPages();
                // #ifdef H5
                if (pages.length > 1) {
                	uni.navigateBack(1)
                	return
                }
                //使用vue-router返回上一级
                let a = this.$router.go(-1)
                if (a == undefined) {
                	//重新定向跳转页面
                	uni.switchTab({
                	    url: '/pages/tabs/mine/mine'
                	});
                }
                return
                // #endif
                if(pages.length <= 1){
                    console.log("返回首页")
                    uni.switchTab({
                        url: '/pages/tabs/home/home'
                    });
                }else {
                    uni.navigateBack(1)
                }

            }
		}
	}
</script>

<style lang="scss" scoped>
    // .wrap {
    // 	display: flex;
    // 	flex-direction: column;
    // 	height: calc(100vh - var(--window-top));
    // 	width: 100%;
    // }
    .swiper-box {
        flex: 1;
        height: 80%;
    }
    .slot-wrap {
    	display: flex;
    	align-items: center;
    	flex: 1;
        .input {
           width: 100%;
           height: 70rpx;
           background: #ededed;
           border-radius: 50rpx;
           display: flex;
           align-items: center;
           justify-content: center;
           .icon {
             background: url(http://yanxuan.nosdn.127.net/hxm/yanxuan-wap/p/20161201/style/img/icon-normal/search2-2fb94833aa.png) center no-repeat;
             background-size: 100%;
             width: 28rpx;
             height: 28rpx;
           }
           text {
             height: 42rpx;
             line-height: 42rpx;
             color: #666;
             padding-left: 10rpx;
             font-size: 30rpx;
			 overflow: hidden;
           }
        }
        .search-wrap {
        	margin: 0 20rpx;
        	flex: 1;
        }
    }
    .navbar-right {
    	margin: 0 24rpx;
    	display: flex;
        .right-item {
        	position: relative;
        	color: #303133;
        	display: flex;
        }
    }
    .scroll-view {
        height: 85%;
        width: 100%;
    }
    .goods-list-view {
        border-radius: 15rpx 15rpx 0rpx 0rpx;
		margin-top: 20rpx;
        .goods-list {
            width: 48%;
            float: left;
            background: #FFFFFF;
            overflow: hidden;
            margin: 10rpx 0;
            border-radius: 20rpx;
            &.list-b {
                margin-left: 24rpx;
            }
        }
    }
    .shop-list-view {
        .shop-view {
            background-color: #FFFFFF;
            margin: 10rpx 16rpx;
            padding: 20rpx 16rpx;
            border-radius: 8rpx;
            margin-bottom: 20rpx;
        }
    }
    .u-tabs-box {
        width: 100%;
        white-space: nowrap;
        position: relative;
    }
    .sort-box {
        position: fixed;
        z-index: 999;
        top: --window-top; /* css变量 */
        left: 0;
        width: 100%;
        height: 80rpx;
        line-height: 80rpx;
        background-color: #FFFFFF;
        .inner-sort {
            position: relative;
        }
        .mask-box {
            position: absolute;
            top: 80rpx;
            width: 100%;
            height: 100vh;
            opacity: 1;
            background-color: rgba(0, 0, 0, 0.6);
            z-index: 99;
            transition: all 0.3s ease-in-out;
            transition: transform 0.3s, -webkit-transform 0.3s;
        }
        .sort-list {
            position: absolute;
            top: 80rpx;
            width: 100%;
            z-index: 999;
            .sort-item {
                border-top: 1rpx solid #f4f4f4;
                background-color: #FFFFFF;
                padding: 20rpx;
                line-height: 40rpx;
            }
        }
        .active {
            color: #ff5000;
        }
    }
    /deep/ {
        .u-drawer-top {
            background-color: #575456 !important;
        }
    }
    .slot-right-box {
        color: #FFFFFF;
        .slot-right-list {
            .slot-right-item {
                width: 25%;
                margin-right: 28rpx;
                padding: 30rpx;
                border-radius: 15rpx;
                background-color: #3E3E3E;
                text-align: center;
                &:last-child {
                    margin-right: 0;
                }
            }
        }
    }
    .auto-complete {
        background-color: #FFF;
        padding: 0 20rpx;
        // height: calc(100% - 100px);
        .auto-complete-item {
            display: flex;
            justify-content: space-between;
            line-height: 60rpx;
            color: #333;
        }
    }

    .history-view {
        background-color: #FFF;
        padding: 20rpx 40rpx;
        .history-text {
            font-weight: 600;
            margin: 20rpx 0rpx;
        }
    }
    .searchShow{
        position: absolute;
        z-index: 9999;
        width: 100%;
        height: 100%;
        top: 0;
        background: #fff;
    }

</style>

